/*
 * Copyright 2018 datagear.tech
 *
 * Licensed under the LGPLv3 license:
 * http://www.gnu.org/licenses/lgpl-3.0.html
 */

package com.bleeth.flow.manager;

import cn.hutool.core.io.FileUtil;
import com.bleeth.flow.core.driver.exception.PluginFactoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * 特定路径JDBC驱动工厂。
 * <p>
 * 此类实例在使用前需要调用其{@linkplain #init()}方法
 * </p>
 *
 * @author datagear@163.com
 */
public class PluginPathFactory {
    private static final Logger LOGGER = LoggerFactory.getLogger(PluginPathFactory.class);

    /**
     * 驱动程序库路径
     */
    private File path;

    private PluginPathClassLoader pluginPathClassLoader;


    public PluginPathFactory(String path) {
        this(FileUtil.newFile(path));
    }

    public PluginPathFactory(File path) {
        super();
        this.path = path;
    }

    public File getPath() {
        return path;
    }

    /**
     * 初始化。
     *
     * @throws PluginFactoryException
     */
    public synchronized void init() throws PluginFactoryException {
        if (this.pluginPathClassLoader != null) {
            return;
        }
        this.pluginPathClassLoader = initPathClassLoader(this.path);
    }


    /**
     * 初始化{@linkplain PluginPathClassLoader}。
     *
     * @param path
     * @return
     */
    protected PluginPathClassLoader initPathClassLoader(File path) {
        PluginPathClassLoader classLoader = new PluginPathClassLoader(path);
        return classLoader;
    }

    /**
     * 获取路径上次修改时间。
     *
     * @return
     */
    public long getPathLastModified() {
        return getPathLastModified(this.path);
    }




    public PluginPathClassLoader getPluginClassLoader() {
        return this.pluginPathClassLoader;
    }

    /**
     * 获取路径的上次修改时间。
     *
     * @param path
     * @return
     */
    protected long getPathLastModified(File path) {
        long pathLastModified = path.lastModified();

        if (path.isDirectory()) {
            File[] children = path.listFiles();

            if (children != null) {
                for (File child : children) {
                    long childLastModified = child.lastModified();
                    if (childLastModified > pathLastModified) {
                        pathLastModified = childLastModified;
                    }
                }
            }
        }
        return pathLastModified;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + " [path=" + path + "]";
    }


}
